package com.taotao.trolley.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.util.JsonUtils;
import com.taotao.pojo.TbItem;
import com.taotao.trolley.service.CartService;
import com.taotao.trolley.service.JedisClient;

@Service
public class CartServiceImpl implements CartService {
	
	//注入jedis
	@Autowired
	private JedisClient jedisClient;
	
	@Value("${TT_CART_PRE_KEY}")
	private String TT_CART_PRE_KEY;
	
	@Override
	public TaotaoResult addItemCart(TbItem item, Integer num, Long userId) {
		//设置商品数量
		item.setNum(num);
		//判断有没有图片
		if(StringUtils.isNotEmpty(item.getImage())) {
			item.setImage(item.getImage().split(",")[0]);
		}
		//购物车内商品存入redis中，用hset(前缀+用户id,商品id,商品内容)
		jedisClient.hset(TT_CART_PRE_KEY+":"+userId, item.getId()+"", JsonUtils.objectToJson(item));
		return TaotaoResult.ok();
	}

	@Override
	public List<TbItem> getCartList(Long userId) {
		
		Map<String, String> map = jedisClient.hgetAll(TT_CART_PRE_KEY+":"+userId);
	
		List<TbItem> list = new ArrayList<TbItem>();
		
		if(null != map) {
			for(Map.Entry<String,String> entry:map.entrySet() ) {
				list.add(JsonUtils.jsonToPojo(entry.getValue(),TbItem.class));
			}
		}
		return list;
	}

	@Override
	public TaotaoResult updateCartByUserId(long userId, long itemId, Integer num) {

		String jsonStr = jedisClient.hget(TT_CART_PRE_KEY+":"+userId, itemId+"");
		
		if(StringUtils.isNotEmpty(jsonStr)) {
			TbItem tbItem = JsonUtils.jsonToPojo(jsonStr, TbItem.class);
			tbItem.setNum(num);
			//设置回redis中
			jedisClient.hset(TT_CART_PRE_KEY+":"+userId, itemId+"",JsonUtils.objectToJson(tbItem));
		}
		
		return TaotaoResult.ok();
	}

	@Override
	public TaotaoResult deleteCartItemById(long userId, long itemId) {
		String jsonStr = jedisClient.hget(TT_CART_PRE_KEY+":"+userId, itemId+"");
		
		if(StringUtils.isNotEmpty(jsonStr)) {
			jedisClient.hdel(TT_CART_PRE_KEY+":"+userId, itemId+"");
		}
		return TaotaoResult.ok();
	}

}
